import * as React from 'react';
import { connect } from 'remax-dva';
import {
  View,
  Image,
  Button,
  Input,
  Form,
  Checkbox,
  Label,
  Text,
  navigateTo,
  showToast,
} from 'remax/wechat';
import { Popup } from 'anna-remax-ui';
import Cell from 'weui-miniprogram/miniprogram_dist/cell/cell'
import Cells from 'weui-miniprogram/miniprogram_dist/cells/cells'
// import Form from 'weui-miniprogram/miniprogram_dist/form/form'
import FormPage from 'weui-miniprogram/miniprogram_dist/form-page/form-page'
import Toptips from 'weui-miniprogram/miniprogram_dist/toptips/toptips'

import clsx from 'clsx';
import useUserInfo from '@/hooks/useUserInfo';
import AddButton from '@/components/AddButton';
import LoginButton from '@/components/LoginButton';
import logo from '@/assets/logo.png';
import './index.css';

const IndexPage = ({ todos, dispatch }) => {
  const [user, login] = useUserInfo();
  const [error, setError] = React.useState('')
  const [formData, setFormData] = React.useState({})
  const [btnName, setBtnName] = React.useState('获取验证码')
  const [canSend, setCanSend] = React.useState(false)
  const [hasSend, setHasSend] = React.useState(false)
  const [codeTime, setCodeTime] = React.useState(10)
  const rules = [ {
    name: 'mobile',
    rules: [{required: true, message: '手机号必填'}, {mobile: true, message: '手机号格式不对'}],
  }, {
    name: 'vcode',
    rules: {required: true, message: '验证码必填'},
  }]

  const handleAdd = async () => {
    navigateTo({ url: '../new/index' });
  };

  /**
   * 检验手机号是否正确
   * @method verifyTel
   * @param {*} number // 手机号
   */
  const verifyTel = (number) => { // 手机号正则校验
    const reg = /^1[3|4|5|7|8|9]\d{9}$/;
    return reg.test(number);
  }
  const onSendCode = (mobile) => {

  }
  const getVCode = (e) => {

    console.log('vcode', e)
    if (canSend) {
      const {
        mobile
      } = formData;
      settimer();
      const pat = /(\d{3})\d*(\d{4})/;
      let str = mobile.replace(pat, '$1***$2');
      onSendCode({
        mobile
      });
      setHasSend(true)
      setCanSend(false)
    } else if (!hasSend){
      setError('请输入正确的手机号')
    }
    e.stopPropagation()
  }
  const settimer = () => {
    let timer;
    let newCodeTime = codeTime
    clearInterval(timer);
    timer = setInterval(() => {
      newCodeTime--;
        setBtnName(`倒计时${newCodeTime}秒`)
        setCanSend(false)
      if (newCodeTime === 0) {
        clearInterval(timer);
        // const box = this.data.othervalue;
        setCanSend(true)
        setBtnName('重新发送')
      }
    }, 1000);
  }

  const bindInput = (e) => {
    onValueInput(e)
    const result = verifyTel(e.detail.value);
    if (result) { // 11位数字
      setCanSend(true)
      setBtnName('获取验证码')
    } else {
      setCanSend(false)
      setBtnName('获取验证码')
    }
    console.log('bindInput',formData, e)
    e.stopPropagation()
  }

  const onValueInput = (e) =>  {
    formData[`${e.currentTarget.dataset.field}`]=e.detail.value
    setFormData(formData)
  }

  const register = () => {
      console.log('register')
  }

  const submitForm = (e) => {
    setError('请输入正确的手机号')
  }

  const handleToggle = (todo) => (e) => {
    dispatch({
      type: 'todo/toggle',
      id: todo.id,
    });
  };

  return (
    <View className="page-todos">
      <View className="page" data-weui-theme="dark">
        <Toptips msg={error} type="error" show={error}></Toptips>
        <FormPage >
      <View className="user">
        <LoginButton login={login}>
          <Image
            className="avatar"
            src={logo}
            background-size="cover"
          />
        </LoginButton>
        <View className="nickname">
          优食家-商家端
        </View>
      </View>
        <Form id="form" onSubmit={e => submitForm(e)} >
        <Cells>
          <Cell prop="mobile" title="手机号" ext-class=" weui-cell_vcode">
            <Input onInput={e => bindInput(e)} data-field="mobile" name="mobile" maxlength="11" className="weui-input" placeholder="请输入手机号"/>
            <View slot="footer" className="weui-vcode-btn" onTap={e => getVCode(e)}>{btnName}</View>
          </Cell>
          <Cell prop="vcode" title="验证码" ext-class=" weui-cell_vcode">
            <Input onInput={e => bindInput(e)} data-field="vcode"  name="vcode" className="weui-input" placeholder="请输入验证码"/>
          </Cell>
        </Cells>
          <View className="weui-btn-area">
            <Button className="weui-btn" type="primary" formType="submit">登录</Button>
            <Button className="weui-btn" type="default" onTap={register}>注册</Button>
          </View>
        </Form>


        </FormPage>
      </View>
    </View>
  );
};

const mapStateToProps = (state) => ({
  todos: state.todo,
});

export default connect(mapStateToProps)(IndexPage);
